package com.danawa.watcher.front;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.danawa.watcher.model.Registration;
import com.danawa.watcher.validation.RegistrationValidator;
import com.danawa.watcherApi.database.domain.Member;
import com.danawa.watcherApi.database.service.WatcherService;

/**
 * @author kevinsong
 * 회원가입 및 로그인 처리를 위한 컨트롤러 
 */
@Controller
public class MemberController {
	
	@Autowired 
	WatcherService watcherService;
	
	@Autowired
	private RegistrationValidator registrationValidator;
	
	public void setRegistrationValidator(
			RegistrationValidator registrationValidator) {
		this.registrationValidator = registrationValidator;
	}
	
	/**
	 * 회원가입 등록 
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/user/regist", method = RequestMethod.GET)
	public String showRegistration(ModelMap modelMap) {
	
		Registration registration = new Registration();
		modelMap.put("registration", registration);
		return "/user/registrationform";
	}
	
	/**
	 * 회원가입 등록 프로세스 
	 * @param registration
	 * @param result
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/user/regist", method = RequestMethod.POST)
	public String processRegistration(@Valid Registration registration,
			BindingResult result,
			ModelMap modelMap) {
		
		/**
		 * 회원가입 입력 폼 검증 
		 */
		registrationValidator.validate(registration, result);
		
		if (result.hasErrors()) {
			return "/user/registrationform";
		}
		
		/**
		 * 회원정보 DB입력 
		 */
		try {
			Member member = new Member();
			member.setEmail(registration.getEmail());
			member.setPassword(registration.getPassword());
			member.setTrackingCount(0);
			
			watcherService.setMember(member);
		} catch (Throwable e) {
			
			modelMap.addAttribute("systemMessage", "중복된 아이디가 입력되었습니다");
			
			// 예외 발생시 등록폼으로 이동
			// TODO:reload시 등록프로세스 안타게 해야한다.
			return "/user/registrationform";
		}
		
		return "/user/loginForm";
	}
	
	/**
	 * 로그인 폼 
	 * @return
	 */
	@RequestMapping(value = "/user/loginform", method = RequestMethod.GET)
	public String loginPage() {
		return "/user/loginForm";
	}
	
	
	
}
